<template>
  <div class="customer-detail">
    <div class="header-container">
      <el-page-header @back="goBack" content="客户详情">
      </el-page-header>
      <el-button-group>
        <el-tooltip effect="dark" content="编辑" placement="top" v-role="['/customer/detail:edit']">
          <el-button type="primary" icon="el-icon-edit" @click="edit(customerForm.cusId)"></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="审核" placement="top" v-role="['/customer/detail:audit']">
          <el-button type="primary" v-if="customerForm.customerStatus =='AUDITING'" icon="el-icon-s-check"
                     @click="audit(customerForm.cusId)">审核
          </el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="入料" placement="top" v-role="['/customer/detail:add']">
          <el-button type="primary" @click="operation(customerForm.cusId, 'add')" v-role="['/customer/detail:add']">
            入料
          </el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="回料" placement="top" v-role="['/customer/detail:add']"
                    v-if="customerForm.customerStatus =='AUTHED'">
          <el-button type="primary" @click="operation(customerForm.cusId, 'sub')">回料</el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="更新客户状态" placement="top" v-role="['/customer/detail:updateStatus']"
                    v-if="customerForm.customerStatus =='AUTHED'">
          <el-button type="primary" icon="el-icon-s-operation" @click="changeState()"></el-button>
        </el-tooltip>
        <el-tooltip effect="dark" content="刷新客户缓存" placement="top" v-role="['/customer/detail:refresh']" >
          <el-button type="primary" icon="el-icon-s-operation" @click="refreshRedis()"></el-button>
        </el-tooltip>
      </el-button-group>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick" style="margin-top: 20px;">
      <el-tab-pane name="detail" label="客户详情">
        <el-card shadow="never">
            <!-- 基本信息 -->
            <el-divider content-position="left">基本信息</el-divider>
          <el-form>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户姓名：" prop="cusName">
                  {{ customerForm.cusName }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户余额：" prop="balance">
                  {{ formatPrice(customerForm.balance) }}
                </el-form-item>
              </el-col>


            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户手机号：" prop="cusPhone">
                  {{ customerForm.cusPhone }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号：" prop="idCardNo">
                  {{ customerForm.idCardNo }}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户状态：" prop="customerStatus">
                  {{ customerStatusMap[customerForm.customerStatus] }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户类型：" prop="customerType">
                  {{ customerTypeMap[customerForm.customerType] }}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户标签：" prop="tag">
                  {{ customerTagMap[customerForm.tag] }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="注册时间：" prop="createDate">
                  {{ customerForm.createDate }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="头像：" prop="avatar">
                  <el-image v-if="customerForm.avatar" :preview-src-list="[IMG_URL + customerForm.avatar]"
                            :src="customerForm.avatar | filter_img" style="width: 100px; height: 100px;"/>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 交易设置 -->
            <el-divider content-position="left">交易设置</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大交易克数：" prop="maxTradeLimit">
                  {{ formatWeight(customerForm.maxTradeLimit) }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否允许交易：" prop="allowTrade">
                  {{ customerForm.allowTrade === 'YES' ? '是' : '否' }}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否内部人员：" prop="isAgent">
                  {{ customerForm.isAgent === 'YES' ? '是' : '否' }}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户风险等级：" prop="riskGrade">
                  {{ riskGradeMap[customerForm.riskGrade] }}
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="客户等级：" prop="grade">
                  {{ gradeMap[customerForm.grade] }}
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 身份证照片 -->
            <el-divider content-position="left">身份证照片</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证人像面：" prop="frontPath">
                  <div class="image-upload-container">
                    <el-image v-if="customerForm.frontPath"
                              :src="IMG_URL + customerForm.frontPath + '?x-oss-process=style/fastview'"
                              :preview-src-list="[IMG_URL + customerForm.frontPath]" fit="cover"
                              class="id-card-image" @click="previewImage(customerForm.frontPath)">
                    </el-image>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证国徽面：" prop="backPath">
                  <div class="image-upload-container">
                    <el-image v-if="customerForm.backPath"
                              :src="IMG_URL + customerForm.backPath + '?x-oss-process=style/fastview'"
                              :preview-src-list="[IMG_URL + customerForm.backPath]" fit="cover"
                              class="id-card-image" @click="previewImage(IMG_URL + customerForm.backPath)">
                    </el-image>

                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 备注信息 -->
            <el-divider content-position="left">备注信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="客户备注：" prop="introduction">
                  {{ customerForm.introduction }}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 客户配置 -->
        <el-card shadow="never" style="margin-top: 20px;">
          <div slot="header" class="config-header">
            <span>客户配置</span>
            <el-button type="primary" size="small" @click="editConfig" v-if="!isEditingConfig">
              编辑配置
            </el-button>
            <div v-else>
              <el-button type="success" size="small" @click="saveConfig" :loading="configLoading">
                保存配置
              </el-button>
              <el-button size="small" @click="cancelEditConfig">取消编辑</el-button>
            </div>
          </div>

          <el-form ref="configForm" :model="customerConfig" :rules="configRules" label-width="140px"
                   :disabled="!isEditingConfig" class="config-form">

            <!-- 推荐人配置 -->
            <el-divider content-position="left">推荐人配置</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="推荐人姓名" prop="referee">
                  <el-input v-model="customerConfig.referee" placeholder="请输入推荐人姓名" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="推荐人ID" prop="refereeId">
                  <el-input v-model="customerConfig.refereeId" placeholder="请输入推荐人ID" clearable/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单克返佣金额" prop="rekeBack">
                  <el-input v-model="customerConfig.rekeBack" placeholder="请输入单克返佣金额" style="width: 100%"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="推荐人提成佣金" prop="refereeCommission">
                  <el-input v-model="customerConfig.refereeCommission" placeholder="请输入推荐人提成佣金"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">元/g</span> -->
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 交易配置 -->
            <el-divider content-position="left">交易配置</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="单笔交易克数限制" prop="singleTradeWeight">
                  <el-input v-model="customerConfig.singleTradeWeight" placeholder="请输入单笔交易克数限制"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">克</span> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最大交易克数" prop="maxTradeLimit">
                  <el-input v-model="customerConfig.maxTradeLimit" placeholder="请输入最大交易克数"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">克</span> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="定金标准" prop="retainerStandard">
                  <el-input v-model="customerConfig.retainerStandard" placeholder="请输入定金标准"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">元</span> -->
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 风险配置 -->
            <el-divider content-position="left">风险配置</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最大亏损金额" prop="maxLoss">
                  <el-input v-model="customerConfig.maxLoss" placeholder="请输入最大亏损金额" style="width: 100%"/>
                  <!-- <span class="unit-text">元</span> -->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="风险损失线" prop="riskLossLine">
                  <el-input v-model="customerConfig.riskLossLine" placeholder="请输入风险损失线"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">元</span> -->
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 业务员配置 -->
            <el-divider content-position="left">业务员配置</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="业务员ID" prop="countermanId">
                  <el-select v-model="customerConfig.countermanId" filterable>
                    <el-option v-for="item in countermanList" :key="item.id" :label="item.userName"
                               :value="item.id"></el-option>
                  </el-select>
                  <!--              <el-input v-model="customerConfig.countermanId" placeholder="请输入业务员ID" clearable/>-->
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务员提成佣金" prop="countermanCommission">
                  <el-input v-model="customerConfig.countermanCommission" placeholder="请输入业务员提成佣金"
                            style="width: 100%"/>
                  <!-- <span class="unit-text">元/g</span> -->
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">

              <el-col :span="12">
                <el-form-item label="企业微信机器人ID" prop="qwRobotId">
                  <el-input v-model="customerConfig.qwRobotId" placeholder="请输入企业微信机器人ID" clearable/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="资金流水" name="fund">
        <CustomerFundList ref="fundListRef" :customer-id="customerId"/>
      </el-tab-pane>
      <el-tab-pane label="订单列表" name="order">
        <CustomerOrderList ref="orderListRef" :customer-id="customerId"/>
      </el-tab-pane>
    </el-tabs>
    <AddOrEdit ref="AddOrEditRef"/>
    <EditDialog ref="EditDialogRef"/>
    <AuditDialog
        ref="AuditDialogRef"
    />
    <!-- 状态选择对话框 -->
    <el-dialog title="更新客户状态" :visible="statusDialogVisible" width="500px" :show-close="true"
               @close="closeStatusDialog" :close-on-click-modal="false">
      <div>
        <p style="margin-bottom: 15px;"><strong>当前用户状态：</strong>{{
            customerStatusMap[customerForm.customerStatus]
          }}</p>
        <p style="margin-bottom: 20px;"><strong>请选择新状态：</strong></p>
        <el-radio-group v-model="selectedNewStatus" style="width: 100%; display: flex; ">
          <el-radio label="AUDITING" style="display: block; margin-bottom: 10px;">审核中</el-radio>
          <el-radio label="AUTHED" style="display: block; margin-bottom: 10px;">已实名</el-radio>
          <el-radio label="ENT_AUTHED" style="display: block; margin-bottom: 10px;">已企业认证</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeStatusDialog">取 消</el-button>
        <el-button type="primary" @click="confirmStatusChange" :loading="statusLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  changeCustomerItemSate,
  getCountermanList,
  getCustomerConfig,
  getCustomerDetail,
  updateCustomerConfig,
  refreshCustomerRedis
} from '../api/customer'
import {IMG_URL} from '@/utils/utils'
import EditDialog from "@/views/property/customer/EditDialog.vue";
import AddOrEdit from "@/views/property/customer/AddOrEdit.vue";
import AuditDialog from "@/views/property/customer/AuditDialog.vue";
import CustomerFundList from './component/CustomerFundList.vue';
import CustomerOrderList from './component/CustomerOrderList.vue';

export default {
  name: 'CustomerDetail',
  components: {AuditDialog, AddOrEdit, EditDialog, CustomerFundList, CustomerOrderList},
  data() {
    return {
      IMG_URL,
      customerId: null,
      customerForm: {},
      customerConfig: {},
      isEditingConfig: false,
      configLoading: false,
      statusLoading: false,
      configRules: {},
      customerStatusMap: {
        AUDITING: '审核中',
        AUTHED: '已实名',
        ENT_AUTHED: '已企业认证',
      },
      customerTypeMap: {
        PERSONAL: '个人',
        ENTERPRISE: '企业',
      },
      customerTagMap: {
        CUSTOMER: '客户',
        AGENT: '代理商',
        REFEREE: '推荐人',
      },
      riskGradeMap: {
        LOW: '低风险',
        MEDIUM: '中风险',
        HIGH: '高风险',
      },
      gradeMap: {
        NORMAL: '普通客户',
        VIP: 'VIP客户',
        DIAMOND: '钻石客户',
      },
      countermanList: [],
      statusDialogVisible: false,
      selectedNewStatus: '',
      activeTab: 'detail',
    }
  },

  mounted() {
    this.customerId = this.$route.query.id
    if (this.customerId) {
      this.getCustomerDetail()
      this.getCustomerConfig()
    }
    this.getCountermanList();
  },

  methods: {
    // 获取客户详情
    async getCustomerDetail() {
      try {
        const res = await getCustomerDetail(this.customerId)
        if (res) {
          this.customerForm = {...res}
          console.log("cusForm:",this.customerForm)
        }
      } catch (error) {
        console.error('获取客户详情失败:', error)
      }
    },

    // 获取客户配置
    async getCustomerConfig() {
      try {
        const res = await getCustomerConfig(this.customerId)
        if (res) {
          this.customerConfig = {...res}
        } else {
          // 如果没有配置数据，初始化默认配置
          this.initDefaultConfig()
        }
      } catch (error) {
        console.error('获取客户配置失败:', error)
        // 初始化默认配置
        this.initDefaultConfig()
      }
    },

    // 初始化默认配置
    initDefaultConfig() {
      this.customerConfig = {
        referee: '',
        refereeId: '',
        rekeBack: 0,
        maxTradeLimit: 0,
        refereeCommission: 0,
        maxLoss: 0,
        riskLossLine: 0,
        retainerStandard: 0,
        qwRobotId: '',
        countermanCommission: 0,
        countermanId: '',
        countermanName: '',
      }
    },
    // 刷新客户缓存
    async refreshRedis() {
      try {
        this.$message.info('正在刷新客户缓存，请稍候...');
        await refreshCustomerRedis(this.customerId);
        this.$message.success('客户缓存刷新成功！');
      } catch (error) {
        console.error('刷新客户缓存失败:', error);
        this.$message.error('刷新客户缓存失败！');
      }
    },
    // 返回
    goBack() {
      this.$router.go(-1)
    },

    // 编辑配置
    editConfig() {
      this.isEditingConfig = true;
      this.$nextTick(() => {
        this.$refs.configForm.clearValidate();
      });
    },

    // 保存配置
    async saveConfig() {
      try {
        this.configLoading = true;
        this.countermanList.forEach(item => {
          if (item.id === this.customerConfig.countermanId) {
            this.customerConfig.countermanName = item.userName;
          }
        });
        const configData = {
          id: this.customerId,
          ...this.customerConfig
        };
        await updateCustomerConfig(configData);
        this.$message.success('客户配置保存成功！');
        this.isEditingConfig = false;
        // 重新获取配置数据
        await this.getCustomerConfig();
      } catch (error) {
        console.error('保存客户配置失败:', error);
        this.$message.error('保存客户配置失败！');
      } finally {
        this.configLoading = false;
      }
    },

    // 取消编辑配置
    cancelEditConfig() {
      this.isEditingConfig = false;
      // 重新获取配置数据，恢复原始值
      this.getCustomerConfig();
    },

    // 预览图片
    previewImage(url) {
      if (url) {
        this.$emit('preview-image', url);
      }
    },
    // 格式化价格
    formatPrice(price) {
      if (price === null || price === undefined || price === '') return '0.00'
      const num = Number(price)
      if (!isFinite(num)) return '0.00'
      return num.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },
    // 重量 千分符
    formatWeight(weight) {
      if (weight === null || weight === undefined || weight === '') return '0'
      const num = Number(weight)
      if (!isFinite(num)) return '0'
      return num.toLocaleString('zh-CN')
    },
    async getCountermanList() {
      const res = await getCountermanList();
      console.log("业务员列表", res);
      this.countermanList = res;
    },
    edit(row) {
      this.$refs.EditDialogRef.open(row);
    },
    audit(row) {
      this.$refs.AuditDialogRef.open(row);
    },
    operation(row, type) {
      this.$refs.AddOrEditRef.operation(row, type);
    },
    changeState() {
      this.selectedNewStatus = '';
      this.statusDialogVisible = true;
    },
    closeStatusDialog() {
      this.statusDialogVisible = false;
      this.selectedNewStatus = '';
    },
    confirmStatusChange() {
      if (!this.selectedNewStatus) {
        this.$message.warning('请选择要更新的状态');
        return;
      }
      if (this.selectedNewStatus === this.customerForm.customerStatus) {
        this.$message.warning('新状态不能与当前状态相同');
        return;
      }
      const data = {
        cusId: this.customerForm.cusId,
        customerStatus: this.selectedNewStatus
      };
      this.statusLoading = true;
      changeCustomerItemSate(data).then(res => {
        this.$message.success('状态更新成功');
        this.closeStatusDialog();
      }).catch(err => {
        this.$message.error('状态更新失败');
      }).finally(() => {
        this.statusLoading = false;
      });
    },

    // Tabs切换处理
    handleTabClick(tab) {
      // 当切换到资金流水标签时，触发资金流水组件的数据加载
      if (tab.name === 'fund') {
        // 切换到资金流水标签时，调用资金流水组件的搜索方法
        this.$nextTick(() => {
          this.$refs.fundListRef && this.$refs.fundListRef.handleSearchFromParent();
        });
      } else if (tab.name === 'order') {
        // 切换到订单列表标签时，调用订单列表组件的搜索方法
        this.$nextTick(() => {
          this.$refs.orderListRef && this.$refs.orderListRef.handleSearchFromParent();
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.header-container .el-button-group {
  margin-left: 30px; /* 按钮与 page-header 的间距 */
}

.customer-detail {
  padding: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.customer-form {
  margin-top: 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.config-form {
  margin-top: 20px;
}

.config-form .el-form-item {
  margin-bottom: 10px;
}

.config-form .el-row {
  margin-bottom: 10px;
}

.config-form .el-divider {
  margin: 30px 0 20px 0;

  ::v-deep .el-divider__text {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.unit-text {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 12px;
  pointer-events: none;
}

.config-form .el-form-item {
  position: relative;
}

.image-upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.id-card-image {
  width: 120px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;

  &:hover {
    border-color: #409eff;
  }
}

.upload-placeholder {
  width: 120px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  &:hover {
    border-color: #409eff;
  }
}

.upload-demo {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  font-size: 20px;
  color: #8c939d;
  margin-bottom: 5px;
}

.upload-text {
  font-size: 12px;
  color: #8c939d;
}

.el-form-item {
  margin-bottom: 5px;
}

.el-row {
  margin-bottom: 0px;
}

// 响应式设计
@media (max-width: 768px) {
  .customer-detail {
    padding: 10px;
  }

  .header-content {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .el-col {
    margin-bottom: 10px;
  }
}
</style>
